<template>
  <div class="chat-page">
    <el-row>
      <view-top></view-top>
    </el-row>
    <el-row>
      <el-col :span="16">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>聊天窗口</span>
          </div>
          <el-scrollbar wrap-class="scrollbar-wrapper">
            <div v-for="message in messages" :key="message.id" class="message">
              <el-avatar :src="message.avatar" size="40"></el-avatar>
              <div class="message-content">
                <p><strong>{{ message.username }}</strong></p>
                <p>{{ message.content }}</p>
              </div>
            </div>
          </el-scrollbar>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>输入框</span>
          </div>
          <el-input v-model="newMessage" placeholder="输入消息内容"></el-input>
          <el-button type="primary" @click="sendMessage">发送</el-button>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import ViewTop from './ViewTop.vue';
export default {
  components: {
    ViewTop
  },
  data() {
    return {
      messages: [],
      newMessage: '',
      socket: null,
      username: JSON.parse(sessionStorage.getItem('user')).username,
      toUsername: ''
    };
  },
  mounted() {
    this.toUsername = this.$route.query.toUser;
    this.socket = new WebSocket(`ws://localhost:8087/chat?username=${this.username}`);
    this.socket.onopen = () => {
      console.log('WebSocket connection established');
    };
    this.socket.onmessage = this.handleMessage;
    this.socket.onclose = this.handleClose;
  },
  methods: {
    sendMessage() {
      if (this.socket.readyState === WebSocket.OPEN) {
        this.socket.send(this.username+":"+this.toUsername+":"+this.newMessage);
        this.messages.push({
          
          avatar: require('../assets/logo.png'),
          username: this.username,
          content: this.newMessage
        });
        this.newMessage = '';
      } else {
        console.error('WebSocket is not open. Cannot send message.');
      }
    },
    handleMessage(event) {
      const message = JSON.parse(event.data);
      this.messages.push({
        
        avatar: message.avatar,
        username: message.userName,
        content: message.content
      });
    },
    handleClose(event) {
      console.log('WebSocket closed:', event);
    }
  }
};
</script>

<style scoped>
.chat-page {
  margin: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.scrollbar-wrapper {
  height: 400px;
}

.message {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
}

.message-content {
  margin-left: 10px;
}
</style>  